#!/usr/bin/env python3
"""
indent MCP Server

面向 indent 软件的 MCP Server，提供命令行操作的封装工具。

MCP tools 列表：
1. indent_format - 使用 indent 命令格式化 C 语言源代码文件
   - 参数：input_file (str): 输入文件路径, output_file (str, 可选): 输出文件路径（默认覆盖原文件）
   - 返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}
"""

import subprocess
import json
from typing import Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("Indent MCP Server")

@mcp.tool()
def indent_format(input_file: str, output_file: Optional[str] = None) -> dict:
    """
    使用 indent 命令格式化 C 语言源代码文件
    
    参数:
        input_file: 要格式化的输入文件路径
        output_file: 格式化后的输出文件路径（可选，默认覆盖原文件）
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 实际执行的命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    try:
        if output_file:
            cmd = ["indent", input_file, "-o", output_file]
        else:
            cmd = ["indent", input_file]
        
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "unknown",
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "unknown",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error executing command: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()